import 'dart:typed_data';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/widget/_.dart';
import 'package:image_pickers/image_pickers.dart';

class ThinkInfoWidget extends StatefulWidget {
  final int thinkCategory;
  final int thinkId;
  ThinkInfoWidget({required this.thinkCategory, required this.thinkId});

  @override
  _ThinkInfoWidget createState() => _ThinkInfoWidget(thinkCategory, thinkId);
}

class _ThinkInfoWidget extends State<ThinkInfoWidget>
    with TickerProviderStateMixin {
  late Think _think;
  late int _thinkCategory;
  late int _thinkId;
  late Future<dynamic> _function;
  ScrollController? _scrollController;
  AnimationController? _animationControllerA;
  AnimationController? _animationControllerB;
  Animation<double>? _iconAnimationA;
  Animation<double>? _iconAnimationB;
  double _opacity = 0.0;
  bool changeDown = true;
  bool changeUp = false;
  late List<Map<String, dynamic>> _titleDataList;
  List<dynamic>? _infoList;
  List<dynamic>? _tagList;

  _ThinkInfoWidget(int thinkCategory, int thinkId) {
    _thinkCategory = thinkCategory;
    _thinkId = thinkId;
  }

  Future<void> likeThisThink() async {
    if (_iconAnimationA!.status == AnimationStatus.forward ||
        _iconAnimationA!.status == AnimationStatus.reverse) {
      return;
    }
    setState(() {
      _think.setIsLike = !_think.isLike!;
      if (_think.isLike!) {
        _think.setThinkLikeType = _think.thinkLikeType! + 1;
      } else {
        _think.setThinkLikeType = _think.thinkLikeType! - 1;
      }
    });
    if (_iconAnimationA!.status == AnimationStatus.dismissed) {
      _animationControllerA!.forward();
    } else if (_iconAnimationA!.status == AnimationStatus.completed) {
      _animationControllerA!.reverse();
    }
    await HomeService.isLikeThink(params: {
      'isLike': _think.isLike,
      'user_Id': SPreferences().getInt('user_Id'),
      'think_Id': _think.id
    });
    if (_think.isLike!) BotToast.showText(text: '点赞成功');
  }

  Future<void> collectionThisThink() async {
    if (_iconAnimationB!.status == AnimationStatus.forward ||
        _iconAnimationB!.status == AnimationStatus.reverse) {
      return;
    }
    setState(() {
      _think.setIsCollection = !_think.isCollection!;
      if (_think.isCollection!) {
        _think.setThinkCollectionType = _think.thinkCollectionType! + 1;
      } else {
        _think.setThinkCollectionType = _think.thinkCollectionType! - 1;
      }
    });
    if (_iconAnimationB!.status == AnimationStatus.dismissed) {
      _animationControllerB!.forward();
    } else if (_iconAnimationB!.status == AnimationStatus.completed) {
      _animationControllerB!.reverse();
    }
    await HomeService.isCollectionThink(params: {
      'isCollection': _think.isCollection,
      'user_Id': SPreferences().getInt('user_Id'),
      'think_Id': _think.id
    });
    if (_think.isCollection!) BotToast.showText(text: '收藏成功');
  }

  Stack title() {
    return Stack(
      children: [
        AnimatedOpacity(
          opacity: _opacity,
          child: Container(
            margin: EdgeInsets.only(
              top: Screen.setHeight(Config.top),
            ),
            height: Screen.setHeight(85),
            width: Screen.width(context),
            child: Center(
              child: Text(
                _think.thinkTitle!,
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          duration: Duration(milliseconds: 350),
        ),
        Container(
          margin: EdgeInsets.only(
            top: Screen.setHeight(Config.top),
          ),
          height: Screen.setHeight(85),
          width: Screen.width(context),
          child: ListTile(
            minVerticalPadding: 0,
            contentPadding: EdgeInsets.all(0),
            leading: IconButton(
              onPressed: () {
                Modular.to.pop();
              },
              icon: Icon(
                Icons.arrow_back,
                color: ColorConfig.BlackObsBackColor,
                size: 20,
              ),
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                GestureDetector(
                  onTap: () async {
                    await likeThisThink();
                  },
                  child:ScaleTransition(
                    scale: _iconAnimationA!,
                    child: Icon(
                      _think.isLike!
                          ? CupertinoIcons.heart_fill
                          : CupertinoIcons.heart,
                      color: _think.isLike!
                          ? ColorConfig.ThemeColor
                          : ColorConfig.BlackObsBackColor,
                      size: 20,
                    ),
                  ) ,
                ),
                SizedBox(
                  width: 5,
                ),
                Text(
                    _think.thinkLikeType! <= 999
                        ? _think.thinkLikeType!.toString()
                        : _think.thinkLikeType! >= 10000
                            ? '${_think.thinkLikeType! ~/ 10000}w+'
                            : '${_think.thinkLikeType! ~/ 1000}k+',
                    style: TextStyle(
                        fontSize: 14,
                        color: _think.isLike!
                            ? ColorConfig.ThemeColor
                            : ColorConfig.BlackObsBackColor)),
                SizedBox(
                  width: 5,
                ),
                GestureDetector(
                  onTap: () async {
                    await collectionThisThink();
                  },
                  child:ScaleTransition(
                    scale: _iconAnimationB!,
                    child:  Icon(
                    _think.isCollection!
                        ? Icons.star
                        : Icons.star_border_outlined,
                    color: _think.isCollection!
                        ? ColorConfig.ThemeColor
                        : ColorConfig.BlackObsBackColor,
                    size: 22,
                  ),
                )
                ),
                SizedBox(
                  width: 5,
                ),
                Text(
                    _think.thinkCollectionType! <= 999
                        ? _think.thinkCollectionType!.toString()
                        : _think.thinkCollectionType! >= 10000
                            ? '${_think.thinkCollectionType! ~/ 10000}w+'
                            : '${_think.thinkCollectionType! ~/ 1000}k+',
                    style: TextStyle(
                        fontSize: 14,
                        color: _think.isCollection!
                            ? ColorConfig.ThemeColor
                            : ColorConfig.BlackObsBackColor)),
                SizedBox(
                  width: 15,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget widgetBlock(String titleItem, Widget child) {
    return Panel(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            child: Text(
              titleItem,
              style: TextStyle(color: ColorConfig.TextColor, fontSize: 13),
            ),
            margin: EdgeInsets.only(left: 5),
          ),
          SizedBox(
            height: 10,
          ),
          Container(
            child: child,
            decoration: BoxDecoration(
                color: ColorConfig.WhiteBackColor,
                borderRadius: BorderRadius.all(Radius.circular(10))),
          )
        ],
      ),
    );
  }

  Panel titleBlock() {
    return Panel(
      top: 10,
      bottom: 10,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          GridView(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, mainAxisSpacing: 5, childAspectRatio: 5),
            shrinkWrap: true,
            padding: EdgeInsets.all(0),
            children: _titleDataList
                .map(
                  (e) => Row(
                    children: [
                      Text(
                        e['title'] + ': ',
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: ColorConfig.BlackBackColor),
                      ),
                      e['title'] != '肖像'
                          ? Text(
                              e['data'],
                              style: TextStyle(
                                  fontSize: 15,
                                  color: e['title'] == '名称'
                                      ? ColorConfig.ThemeColor
                                      : ColorConfig.BlackBackColor),
                            )
                          : ClipRRect(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(15)),
                              child: Container(
                                width: 30,
                                height: 30,
                                child: Image(
                                  image: NetworkImage(
                                    e['data'],
                                  ),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                    ],
                  ),
                )
                .toList(),
          ),
          SizedBox(
            height: 5,
          ),
          Text(
            '简述：${_infoList![0]}',
            style: TextStyle(color: ColorConfig.BlackBackColor),
          )
        ],
      ),
    );
  }

  /// 保存图片到相册
  saveGallery(String url) async {
    var response = await PublicService.downImage(url: url, params: {});
    String fileName = Tool.randomBit();
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response),
        quality: 100,
        name: fileName
    );
    result['isSuccess']
        ? BotToast.showText( text: '图片存储在 ${result['filePath']}')
        : BotToast.showText( text:"保存失败");
  }


  Widget contentWidget() {
    return Panel(
      top: 10,
      bottom: 10,
      child: Text.rich(
        TextSpan(
          style: TextStyle(
            fontSize: 16,
            color: ColorConfig.BlackBackColor,
          ),
          children: _infoList!.asMap().keys.map((e) {
            return TextSpan(
              text: '  ' + _infoList![e] + '\n\n',
              children: e == 0
                  ? [
                      WidgetSpan(

                        child: GestureDetector(
                          onTap: (){
                            ImagePickers.previewImage(_think.thinkIndexImageUrl!);

                          },
                          onLongPress: () async {
                            await showDialog(
                                context: context,
                                builder: (context) {
                                  return SimpleDialog(
                                    titlePadding: EdgeInsets.all(15),
                                    contentPadding: EdgeInsets.all(15),
                                    title: Container(
                                      alignment: Alignment.centerLeft,
                                      child: Row(
                                        children: [
                                          Icon(Icons.touch_app,size: 30,color: ColorConfig.ThemeColor,),
                                          SizedBox(width: 5,),
                                          Text("请选择操作",style: TextStyle(fontSize: 17),)
                                        ],
                                      ),
                                    ),
                                    children: <Widget>[
                                      TextButton(
                                          child: Text("保存到相册",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                          onPressed: () async {
                                            Navigator.of(context).pop();
                                            await saveGallery(_think.thinkIndexImageUrl!
                                                );
                                          }
                                      ),

                                    ],
                                  );
                                }
                            );
                          },
                          child: Image.network(
                            _think.thinkIndexImageUrl!,
                              filterQuality:FilterQuality.high
                          ),
                        )),
                      TextSpan(text: '\n')
                    ]
                  : null,
            );
          }).toList(),
        ),
      ),
    );
  }

  Widget tagWidget() {
    return Panel(
        top: 10,
        bottom: 10,
        right: 10,
        child: Container(
          height: Screen.setHeight(60),
          padding: EdgeInsets.only(top: 10),
          child: ListView(
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            scrollDirection: Axis.horizontal,
            children: _tagList!
                .asMap()
                .keys
                .map((e) => Row(
                      children: [
                        Container(
                          margin: EdgeInsets.only(bottom: 10),
                          padding: EdgeInsets.only(left: 5, right: 5),
                          decoration: BoxDecoration(
                            color: ColorConfig.WhiteBackColor,
                            border: Border(
                                left: BorderSide(
                                    color: Colors
                                        .primaries[e % Colors.primaries.length],
                                    width: 5),
                                top: BorderSide(
                                  color: Colors
                                      .primaries[e % Colors.primaries.length],
                                  width: 1,
                                ),
                                bottom: BorderSide(
                                  color: Colors
                                      .primaries[e % Colors.primaries.length],
                                  width: 1,
                                ),
                                right: BorderSide(
                                  color: Colors
                                      .primaries[e % Colors.primaries.length],
                                  width: 2,
                                )),
                          ),
                          child: Align(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              _tagList![e],
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 15,
                        )
                      ],
                    ))
                .toList(),
          ),
        ));
  }

  @override
  void initState() {
    super.initState();
    setIconAnimated();
    _function = future();
  }

  @override
  void dispose() {
    _scrollController!.dispose();
    _animationControllerA!.dispose();
    _animationControllerB!.dispose();
    super.dispose();
  }

  future() async {
    await HomeService.setRecentVisit(params: {
      'recentVisit_Type':0,
      'user_Id':SPreferences().getInt('user_Id'),
      'thing_Id':_thinkId
    });
    await getInfoData();
  }

  Future<void> getInfoData() async {
    Think res = await HomeService.getThinkInfo(params: {
      'think_Category': _thinkCategory,
      'think_Id': _thinkId,
      'user_Id': SPreferences().getInt('user_Id')
    });
    _think = res;
    _scrollController = ScrollController();
    listenTitle();
    switch (_thinkCategory) {
      case 0:
        _titleDataList = [
          {"title": '名称', 'data': _think.thinkTitle},
          {"title": '时间', 'data': _think.thinkTimes},
          {"title": '时代', 'data': _think.thinkTime!.timeTitle},
          {"title": '地区', 'data': _think.thinkCountry!.name},
        ];
        _infoList = _think.thinkInfo!.thinkInfo!;
        _tagList = _think.thinkInfo!.thinkTagList!;
        return;
      case 2:
        _titleDataList = [
          {"title": '名称', 'data': _think.thinkTitle},
          {"title": '完成时间', 'data': _think.thinkTimes},
          {"title": '作者', 'data': _think.thinkPaint!.paintUserName},
          {"title": '肖像', 'data': _think.thinkUserImage},
          {"title": '题材', 'data': _think.thinkPaint!.paintTheme},
          {"title": '风格流派', 'data': _think.thinkPaint!.paintStyle},
          {"title": '材质', 'data': _think.thinkPaint!.paintRow},
          {"title": '题材', 'data': _think.thinkPaint!.paintTheme},
          {"title": '时代', 'data': _think.thinkTime!.timeTitle},
          {"title": '收藏地点', 'data': _think.thinkPaint!.paintCollection},
        ];
        _infoList = _think.thinkPaint!.paintInfo!;
        _tagList = _think.thinkPaint!.paintTagList!;
        return;
      case 3:
        _titleDataList = [
          {"title": '名称', 'data': _think.thinkTitle},
          {"title": '完成时间', 'data': _think.thinkTimes},
          {"title": '作者', 'data': _think.thinkAncient!.ancientUserName},
          {"title": '肖像', 'data': _think.thinkUserImage},
          {"title": '书籍领域', 'data': _think.thinkAncient!.ancientType},
          {"title": '书籍派别', 'data': _think.thinkAncient!.ancientPosition},
          {"title": '时代', 'data': _think.thinkTime!.timeTitle},
          {"title": '国籍', 'data': _think.thinkCountry!.name},
        ];
        _infoList = _think.thinkAncient!.ancientInfo!;
        _tagList = _think.thinkAncient!.ancientTagList!;
        return;
    }


  }

  void setIconAnimated() {
    _animationControllerA =
        AnimationController(duration: Duration(milliseconds: 300), vsync: this);
    _animationControllerB =
        AnimationController(duration: Duration(milliseconds: 300), vsync: this);
    _iconAnimationA = TweenSequence([
      TweenSequenceItem(
          tween: Tween(begin: 1.0, end: 1.3)
              .chain(CurveTween(curve: Curves.easeIn)),
          weight: 50),
      TweenSequenceItem(tween: Tween(begin: 1.3, end: 1.0), weight: 50),
    ]).animate(_animationControllerA!);
    _iconAnimationB = TweenSequence([
      TweenSequenceItem(
          tween: Tween(begin: 1.0, end: 1.3)
              .chain(CurveTween(curve: Curves.easeIn)),
          weight: 50),
      TweenSequenceItem(tween: Tween(begin: 1.3, end: 1.0), weight: 50),
    ]).animate(_animationControllerB!);
  }

  void listenTitle() {
    _scrollController!.addListener(() {
      if (_scrollController!.offset > 65 && changeDown) {
        setState(() {
          _opacity = 1.0;
          changeDown = false;
          changeUp = true;
        });
      }
      if (_scrollController!.offset < 65 && changeUp) {
        setState(() {
          _opacity = 0.0;
          changeDown = true;
          changeUp = false;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _function,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        return snapshot.connectionState == ConnectionState.done
            ? Empty(
                child: Scaffold(
                  backgroundColor: ColorConfig.LineColor,
                  appBar: PreferredSize(
                    preferredSize: Size.fromHeight(55),
                    child: title(),
                  ),
                  body: Container(
                    child: ListView(
                      controller: _scrollController,
                      physics: BouncingScrollPhysics(),
                      shrinkWrap: true,
                      children: [
                        widgetBlock('基础信息', titleBlock()),
                        widgetBlock(_thinkCategory == 0 ? '事件详情' : _thinkCategory == 2 ?'画作详情':'书籍详情',
                            contentWidget()),
                        widgetBlock('相关标签', tagWidget())
                      ],
                    ),
                  ),
                ),
                isShow: _think.id == null,
              )
            : Scaffold(
                body: Loading(),
              );
      },
    );
  }
}
